import React, { useState, useEffect } from "react";
import { Modal, Tabs, Select, Alert, ConfigProvider } from "antd"; // 引入 Alert
import LineChart from "./LineChart";
import { zbList, zbChart } from "@/api/Home/home";

interface EchartstabsProps {
  open: boolean;
  onClose: () => void;
}

const Echartstabs: React.FC<EchartstabsProps> = ({ open, onClose }) => {
  const [activeKey, setActiveKey] = useState("1");
  const [optiondata, setOptiondata] = useState<any>({});
  const [analysisText, setAnalysisText] = useState<string>(""); // 存储 text 字段
  const [selectOptions, setSelectOptions] = useState<{
    dayList: string[];
    weekList: string[];
    zbList: string[];
  }>({ dayList: [], weekList: [], zbList: [] });
  const [selectedValue, setSelectedValue] = useState<string | undefined>(
    undefined
  );

  useEffect(() => {
    zbListApi();
  }, []);

  const zbListApi = async () => {
    const res = await zbList();
    setSelectOptions({
      dayList: res.data.dayList || [],
      weekList: res.data.weekList || [],
      zbList: res.data.zbList || [],
    });
  };

  const tabTypeMap: Record<string, "day" | "week" | "zb"> = {
    "1": "day",
    "2": "week",
    "3": "zb",
  };

  useEffect(() => {
    let dropdownList: string[] = [];
    if (activeKey === "1") dropdownList = selectOptions.dayList;
    else if (activeKey === "2") dropdownList = selectOptions.weekList;
    else if (activeKey === "3") dropdownList = selectOptions.zbList;

    if (dropdownList.length > 0) {
      const firstValue = dropdownList[0];
      setSelectedValue(firstValue);
      fetchChartData(firstValue, activeKey);
    } else {
      setSelectedValue(undefined);
      setOptiondata({});
      setAnalysisText(""); // 重置 text
    }
  }, [activeKey, selectOptions]);

  const fetchChartData = async (value: string, key: string) => {
    try {
      const res: any = await zbChart({ type: tabTypeMap[key], zbName: value });
      if (res.code === 1) {
        setOptiondata({
          title: { text: `${value} 趋势图` },
          xAxis: { type: "category", data: res.data.xAxis },
          yAxis: { type: "value" },
          series: res.data.series.map((s: any) => ({
            name: `${s.name}`,
            type: "line",
            data: s.data,
            unit: s.unit,
          })),
        });

        // 如果是分析页，存储 text
        if (key === "3") {
          setAnalysisText(res.text || "");
        } else {
          setAnalysisText("");
        }
      }
    } catch (e) {
      console.error("zbChart接口异常", e);
    }
  };

  let dropdownList: string[] = [];
  if (activeKey === "1") dropdownList = selectOptions.dayList;
  else if (activeKey === "2") dropdownList = selectOptions.weekList;
  else if (activeKey === "3") dropdownList = selectOptions.zbList;

  return (
    <Modal
      title="数据分析"
      open={open}
      width={"85%"}
      onCancel={onClose}
      footer={null}
    >
      <Tabs
        activeKey={activeKey}
        type="card"
        onChange={(key) => setActiveKey(key)}
        items={[
          { key: "1", label: "日报" },
          { key: "2", label: "周报" },
          { key: "3", label: "分析" },
        ]}
      />

      {/* 下拉选择器 */}
      <div className="flex min-w-full">
        <div className="mr-4">
          <Select
            style={{ width: 240 }}
            placeholder="请选择指标"
            value={selectedValue}
            onChange={(value) => {
              setSelectedValue(value);
              if (value) fetchChartData(value, activeKey);
            }}
            options={dropdownList.map((item) => ({ label: item, value: item }))}
            allowClear
          />
        </div>

        {/* 分析页才显示 text */}
        {activeKey === "3" && analysisText && (
          <ConfigProvider
            theme={{
              components: {
                Alert: {
                 withDescriptionPadding:'6px'
                },
              },
            }}
          >
            <Alert
              className="flex-1 ml-4"
              description={
                <pre style={{ whiteSpace: "pre-wrap", margin: 0 }}>
                  {analysisText}
                </pre>
              }
              style={{ margin: "3px" }}
            />
          </ConfigProvider>
        )}
      </div>

      <LineChart option={optiondata} />
    </Modal>
  );
};

export default Echartstabs;
